const fs = require("fs");
const { downloadFile, isDownloadFileURL, getMusicExceptionIndex, } = require("../assets/util");
const { SINGER_LIST, ROOT_DIR } = require('../assets/config')
/**
 *
 * @param {*} browser 浏览器对象
 * @param {*} page 页面对象
 * @param {*} index 数组下标
 * @returns
 */
const getMusicDownloadUrlList = async (browser, page, index, url = "", singerName = '') => {
  console.log("-------singerName------", singerName)
  let musicName = ''
  try {
    console.log("index: ", index);
    await page.waitForSelector("div.arco-col.text-right > button");
    const musicEleList = await page.$$("div.arco-col.text-right > button");
    console.log("musicEleList: ", musicEleList.length);

    //新一轮下载
    const length = musicEleList.length || 1;
    if (length < index + 1) {
      console.log("----end current singer music crawler---");
      const singerIndex = SINGER_LIST.findIndex((singer) => singer.name === singerName);
      const singer = SINGER_LIST[singerIndex + 1]
      if (!singer) {
        browser.close();
        return
      }
      const isExist = fs.existsSync(`${ROOT_DIR}/${singer.name}`);
      !isExist && fs.mkdirSync(`${ROOT_DIR}/${singer.name}`);
      console.log('---------- start next singer -------' + singer.name);
      await page.goto(singer?.url, { waitUntil: "domcontentloaded" });
      console.log('----- page loaded success ----')
      await getMusicDownloadUrlList(browser, page, 0, singer?.url, singer.name);
      return;
    }
    const currentEle = musicEleList[index];
    await currentEle?.click();
    const eleList = await page.$$(".mx-menu-ghost-host .mx-context-menu-item");
    eleList[eleList.length - 1]?.click();
    //获取a标签列表
    await page.waitForSelector("div.arco-modal-body > div");
    musicName = await page.$eval(
      "div.arco-modal-body > div > input",
      (ele) => {
        const txt = ele?.value?.split('-')[0]
        return `${txt}`;
      }
    );
    console.log("musicName: ", musicName);
    const downloadHrefList = await page.$$eval(
      "div.arco-modal-body > div a",
      (downloadEleList) => {
        return downloadEleList.map((option) => {
          return {
            txt: option.textContent,
            href: option.href,
            class: option.class,
            //1:歌词 2:歌曲
            type: option.textContent?.indexOf(".lrc") > -1 ? 1 : 2,
          };
        });
      }
    );
    console.log("---- download list -----: ", downloadHrefList[0]);
    const musicInfo = downloadHrefList?.find(
      (ele) => ele.txt.indexOf("高品") > -1 && !!ele.href
    );
    const musicLyricInfo = downloadHrefList?.find((ele) => ele?.type === 1);
    console.log("musicLyricInfo: ", musicLyricInfo);

    if (musicInfo?.href) {
      //下载歌词
      const lyricUrl = musicLyricInfo?.href;
      console.log("------------下载歌词");
      await downloadFile(lyricUrl, `${musicName}-${singerName}.lrc`, singerName);
      const isValidDownloadLink = await isDownloadFileURL(musicInfo?.href);
      console.log("isValidDownloadLink: ", isValidDownloadLink);
      if (!isValidDownloadLink) {
        await page.goto(musicInfo?.href);
        console.log('page.url(): ', page.url());

        //小飞机网盘
        if (page.url().includes('share.feijipan')) {
          await page.waitForSelector('.down-btn');
          const downloadEle = await page.$('.down-btn');
          console.log('downloadEle: ', downloadEle);
          downloadEle.click();
          setTimeout(async () => {
            await page.goto(url, { waitUntil: "domcontentloaded" });
            await getMusicDownloadUrlList(browser, page, index + 1, url, singerName);
          }, 1000)
          return
        }

        //iframe 处理
        await page.waitForSelector('iframe')
        const framePage = await page.frames().find(f => {
          const frameUrl = f.url();
          console.log('----- frame page url', frameUrl)
          return frameUrl.indexOf('/fn') > -1
        }); // 替换为你的iframe名称
        if (framePage) {
          await framePage.waitForSelector('a');
          console.log('----- frame page ----')
          // 在iframe中执行操作，例如获取文本
          const downloadLink = await framePage.$('a'); // 替换为你想获取内容的选择器和需要执行的操作
          console.log('---- downloadLink ----', downloadLink)
          downloadLink.click();
          try {
            await page.goto(downloadLink)
          } catch (e) {
            setTimeout(async () => {
              await page.goto(url, { waitUntil: "domcontentloaded" });
              const i = index + 1;
              await getMusicDownloadUrlList(browser, page, i, url, singerName);
            }, 2000);
          }
          return
        }
        // await page.reload();
      } else {
        console.log('---- 00 ----', singerName)
        await downloadFile(musicInfo?.href, `${musicName}-${singerName}.mp3`,singerName);
        await page.$eval("div.arco-modal-close-btn", async (ele) => {
          if (ele) {
            ele?.click();
          } else {
            await page.reload();
          }
          return ele;
        });
      }

    }

    setTimeout(async () => {
      const i = index + 1;
      await getMusicDownloadUrlList(browser, page, i, url, singerName);
    }, 500);
  } catch (e) {
    console.log('---- error ---', e)
    console.log("------服务出错-------", url);
    const i = getMusicExceptionIndex(singerName, musicName, index, url)
    console.log('reload start', i)
    if (url !== page.url()) {
      await page.goto(url, { waitUntil: "domcontentloaded" });
      console.log('reload success')
    }
    await getMusicDownloadUrlList(browser, page, i, url, singerName);

  }
};

module.exports = {
  getMusicDownloadUrlList,
};
